import json

from django.http import HttpResponseForbidden
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from django import http
import re

from django_redis import get_redis_connection

from apps.users.models import User
from apps.users.utils import generate_verify_email_url

from utils.response_code import RETCODE
from django.contrib.auth.mixins import LoginRequiredMixin



from utils.secret import SecretOauth


# 展示收货地址
class AddressView(View):
    def get(self, request):
        context= {
            'address':[],
            'default_address_id':''

        }
        return render(request, 'user_center_site.html', context)

# 激活邮箱
class EmailVerifyView(LoginRequiredMixin, View):
    def get(self, request):
        """实现邮箱验证逻辑"""
        # 接收参数
        token = request.GET.get('token')
        # 解密
        data_dict = SecretOauth().loads(token)

        user_id = data_dict.get('user_id')
        email = data_dict.get('email')

        # 校验参数：判断token是否为空和过期，提取user
        try:
            user = User.objects.get(id=user_id, email=email)
        except Exception as e:
            print(e)
            return http.HttpResponseForbidden('无效的token')

        # 修改email_active的值为True
        user.email_active = True
        user.save()
            # return http.HttpResponseServerError('激活邮件失败')

        # 返回邮箱验证结果
        return redirect(reverse('users:info'))

# 保存邮箱
class EmailView(LoginRequiredMixin ,View):
    def put(self, request):

        # 接受参数
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')
        # 校验 正则
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('参数email有误')
        # 修改数据
        request.user.email = email
        request.user.save()

        # 发邮件
        verify_url = generate_verify_email_url(request.user)

        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(email, verify_url)

        # 返回响应对象
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})
# 用户中心
class UserInfoView(LoginRequiredMixin, View):
    def get(self, request):

        # 去数据库查询个人信息
        user = request.user
        context = {
            'username': user.username,
            'mobile': user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }

        return render(request, 'user_center_info.html', context)

# 退出登录
class LogOutView(View):
    def get(self, request):
        # 清除  登录状态session
        from django.contrib.auth import logout
        logout(request)
        # 清除 cookie
        response = redirect(reverse('contents:index'))
        response.delete_cookie('username')
        # 重定向到首页
        return response

# 登录
class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        # 后台接收 解析参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')
        # 校验判空
        if not all([username, password]):
            return HttpResponseForbidden('参数不齐全')
            # 2.1 用户名
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return HttpResponseForbidden('请输入5-20个字符的用户名')
            # 2.2 密码
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden('请输入8-20位的密码')
        # from表单  非表单  headers


        # 判断用户名和密码是否正确
        from django.contrib.auth import authenticate, login
        user = authenticate(username=username, password=password)
        # 判断user是否存在  不存在表示登录失败
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
        # 保持登录状态
        login(request, user)
        # 5.是否记住用户名
        if remembered != 'on':
            # 不记住用户名, 浏览器结束会话就过期
            request.session.set_expiry(0)
        else:
            # 记住用户名, 浏览器会话保持两周
            request.session.set_expiry(None)

        # 操作next
        next = request.GET.get('next')
        if next:
            response =  redirect(next)
        else:
            response = redirect(reverse('contents:index'))
        # 存用户名到cookie里边去
        response.set_cookie('username', user.username, max_age=2 * 14 * 24 * 3600)

        # 跳转到首页
        return response

# 判断手机号是否重复
class MobilecountView(View):
    def get(self, request, mobile):


        # 接收参数

        # 校验正则

        # 业务逻辑判断
        count = User.objects.filter(mobile=mobile).count()
        # 返回响应对象
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})

# 判断用户名是否重复
class UsernamecountView(View):
    def get(self, request, username):

        # 接收参数


        # 校验正则


        # 业务逻辑判断
        count = User.objects.filter(username=username).count()

        # 返回响应对象
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


# 注册视图
class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')
    # 接受参数
    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')

        # 校验   判空---正则
        # if not all([username, password, password2, mobile]):
        #     return http.HttpResponseForbidden("缺少参数！")
        # # 用户名 正则判断  是否重复
        # if not re.match('^[a-zA-Z0-9_-]{5,20}$', username):
        #     return http.HttpResponseForbidden("请输入5-20个字符的用户")
        # # 正则验证密码
        # if not re.match('^[0-9A-Za-z]{8,20}$', password):
        #     return http.HttpResponseForbidden("请输入8-20位的密码")
        # # 两次是否一致
        # if password != password2:
        #     return http.HttpResponseForbidden("两次密码不一致")
        # # 正则判断手机号
        # if not re.match('^1[345789]\d{9}$', mobile):
        #     return http.HttpResponseForbidden("请输入正确的手机号码")
        # # 勾选
        # if allow != 'on':
        #     return http.HttpResponseForbidden("请勾选同意")
        #
        # # 判断短信验证码是否正确
        # sms_code = request.POST.get('msg_code')
        # redis_sms_client = get_redis_connection('sms_code')
        # redis_sms_code = redis_sms_client.get('sms_%s' % mobile)
        # if not redis_sms_code:
        #     return render(request, 'register.html', {'sms_code_errmsg': '无效的短信验证码'})
        # redis_sms_client.delete('sms_%s' % mobile)
        # if sms_code != redis_sms_code.decode():
        #     return render(request, 'register.html', {'sms_code_errmsg': '短信验证码不正确!'})
        # 3.注册
        user = User.objects.create_user(username=username, password=password, mobile=mobile)
        # 保持登录状态
        from django.contrib.auth import login
        login(request, user)
        # 重定向
        return redirect(reverse('contents:index'))
        # return http.HttpResponse('首页')